<?php


namespace App\Listeners;

use App\Events\OrderDelivery;
use App\Models\Escort;
use App\Models\Group;
use App\Models\Order;
use App\Models\User;
use App\Services\BalanceService;
use App\Services\NoticeService;

/**
 * 送达后更新
 * Class OrderDeliveryUpdateListener
 * @package App\Listeners
 */
class OrderDeliveryUpdateListener
{
    /** @var Order */
    public $order;

    /**
     * Handle the event.
     *
     * @param  OrderDelivery $event
     * @return void
     * @throws \Throwable
     */
    public function handle(OrderDelivery $event)
    {
        $this->order = $event->order;

        $this->doLegwork();
    }

    /**
     * 瓜瓜配送更新字段
     */
    private function doLegwork()
    {
//        if(!$this->order->out_trade_no){
//            $escort = $this->order->escort;
//            //如果镖头自己送的，钱结算到镖头身上
//            if($escort->role >= 2){
//                $user = $escort->user;
//                $user->balance += $this->order->pay_price;
//                $user->save();
//            }else{
//                $user = User::whereKey($escort->leader)->first();
//                $user->balance += $this->order->pay_price;
//                $user->save();
//            }
//            //余额明细
//            BalanceService::addCreditLog(24, $user->id, 1, $this->order->pay_price, $user->balance, "下级镖师{$escort->realname}配送您获得{$this->order->pay_price}", 0, 0, 0, $user->give_balance, $this->order->id);
//        }
        //配送员的累计单子加1
        $escort_info = Escort::find($this->order->escort_id);
        $escort_info->counts = $escort_info->counts+1;
        $escort_info->save();

        //通知第三方外卖平台订单状态
        $group = Group::whereAppId($this->order->uid)->first();
        if($group){
            //通知配送成功
            info('配送完成通知');
            NoticeService::send_order($this->order,3,$group->callback);
        }

    }
}
